import { pickBy } from 'lodash';
import { LawCurve } from './types';

export const getDefaultLawCurveValue = (start = 20) =>
  JSON.stringify({
    type: 'Constant',
    start,
    end: 0,
    bsplineId: '',
  });

export const getLawCurveFromJSONString = (value: string) => {
  // the only way a value is passed here is if it was previously produced by JSON.stringify on a valid LawCurve object
  // try-catch is not needed here
  const { type, start, end, bsplineId } = JSON.parse(value) as LawCurve;

  return pickBy(
    {
      type,
      start: ['Constant', 'S', 'Linear'].includes(type) ? start : null,
      end: ['S', 'Linear'].includes(type) ? end : null,
      bsplineId: type === 'BSpline' ? bsplineId : null,
    },
    (v) => v != null,
  ) as unknown as LawCurve;
};

export const isLawCurveValid = (value: string) => {
  const { type, start, end, bsplineId } = getLawCurveFromJSONString(value);

  if (type === 'Constant') {
    return start != null;
  }

  if (type === 'Linear' || type === 'S') {
    return start != null && end != null;
  }

  return !!bsplineId;
};
